/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.toko.dao.impl;

import com.toko.dao.TransactionDAO;
import com.toko.model.Transaction;
import com.toko.model.TransactionDetail;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import org.joda.time.DateTime;

/**
 *
 * @author Benny
 */
public class TransactionDAOImpl implements TransactionDAO {

    private Connection conn;

    public TransactionDAOImpl(Connection conn) {
        this.conn = conn;
    }

    @Override
    public void insert(Transaction transaction) throws Exception {
        
        DateTime date = new DateTime();
        String sql1 = "INSERT INTO transaction(id,transaction_date,transaction_number,customer_id) "
                + "VALUES(?,?,?,?)";
        String sql2 = "INSERT INTO transaction_detail(transaction_id,item_id,quantity,transaction_price) "
                + "VALUES(?,?,?,?)";
        this.conn.setAutoCommit(false);
        try {
            PreparedStatement st = this.conn.prepareStatement(sql1);
            st.setInt(1, transaction.getId());
            st.setString(2, date.toString("yyyy-MM-dd"));
            st.setString(3, transaction.getTransactionNumber());
            st.setInt(4, transaction.getCustomer().getId());
            st.executeUpdate();
            for (TransactionDetail detail : transaction.getDetails()) {
                PreparedStatement st2 = this.conn.prepareStatement(sql2);
                st2.setInt(1, transaction.getId());
                st2.setInt(2, detail.getItem().getId());
                st2.setInt(3, detail.getQuantity());
                st2.setDouble(4, Double.parseDouble(transaction.getTransactionNumber()));
                st2.executeUpdate();
                this.conn.commit();
                st2.close();
                st2 = null;
            }
            st.close();
        } catch (Exception ex) {
            this.conn.rollback();
            throw ex;
        } finally {
            this.conn.setAutoCommit(true);
        }
    }

    @Override
    public void delete(int id) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void update(int olId, Transaction transaction) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Transaction getOrder(int id) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Transaction> getTransaction() throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Transaction> getTransactionByCustomer(int customerId) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
